package com.school.config;


import com.school.domain.vo.Result;
import io.swagger.v3.oas.annotations.Hidden;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 */
@Slf4j
@Order(1)
@RestControllerAdvice
@Hidden   // 解决knife4j文档报错问题
public class WebGlobalExceptionConfig {

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handleMethodArgumentNotValidException(@NotNull MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        log.warn("参数校验失败: {}", message);
        return Result.fail(400, message);
    }

    /**
     * 处理参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    public Result<?> handleBindException(@NotNull BindException e) {
        String message = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        log.warn("参数绑定失败: {}", message);
        return Result.fail(400, message);
    }

    /**
     * 处理约束违反异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<?> handleConstraintViolationException(@NotNull ConstraintViolationException e) {
        String message = e.getConstraintViolations().stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining(", "));
        log.warn("约束违反: {}", message);
        return Result.fail(400, message);
    }

    /**
     * 处理资源未找到异常
     */
    @ExceptionHandler({NoResourceFoundException.class, NoHandlerFoundException.class})
    public void handleResourceNotFoundException(Exception e) {
    }

    /**
     * 处理请求方法不支持异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<?> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.warn("请求方法不支持: {}", e.getMessage());
        return Result.fail(405, "不支持'" + e.getMethod() + "'请求方法");
    }

    /**
     * 处理媒体类型异常
     */
    @ExceptionHandler({HttpMediaTypeNotSupportedException.class, HttpMediaTypeNotAcceptableException.class})
    public Result<?> handleHttpMediaTypeException(Exception e) {
        log.warn("媒体类型错误: {}", e.getMessage());
        return Result.fail(415, "不支持的媒体类型");
    }

    /**
     * 处理请求参数绑定异常
     */
    @ExceptionHandler({ServletRequestBindingException.class, HttpMessageNotReadableException.class})
    public Result<?> handleServletRequestBindingException(Exception e) {
        log.warn("请求参数绑定错误: {}", e.getMessage());
        return Result.fail(400, "请求参数错误");
    }

    /**
     * 处理SpringDoc相关异常，确保不影响系统其他功能
     */
    @ExceptionHandler({NoSuchMethodError.class})
    public Result<?> handleSpringDocCompatibilityException(NoSuchMethodError e) {
        String message = e.getMessage();
        if (message != null && message.contains("ControllerAdviceBean") && message.contains("springdoc")) {
            log.error("SpringDoc兼容性错误 (不影响核心功能): {}", message);
            return Result.fail(500, "API文档系统暂时不可用，但不影响系统正常使用");
        }
        throw e;
    }

    @ExceptionHandler({SQLIntegrityConstraintViolationException.class, DuplicateKeyException.class})
    public Result<?> handleSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e) {
        log.warn("数据库完整性约束违反: {}", e.getMessage());
        return Result.fail(400, "数据已存在或不符合要求");
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e) {
        log.error("系统异常", e);
        return Result.fail(500, e.getMessage());
    }
}
